<template>
  <div class="h-cropper" @click="handleClick">
    <i class="h-icon avatar-cropper-icon" v-if="!cropperImage">
      <h-icon icon="fa-plus"></h-icon>
    </i>
    <input
      class="h-cropper__input"
      name="file"
      accept=""
      type="file"
      ref="inputRef"
      @change="handleChange"
    />
    <!-- 剪切后的图片 -->
    <img class="cropperImg" :src="cropperImage" v-if="cropperImage" />
  </div>

  <!-- 模态窗 -->
  <div class="h-overlay" style="z-index: 2002" v-if="showWindow">
    <div class="h-overlay-dialog">
      <div class="h-dialog">
        <div class="h-dialog__body">
          <img
            style="width: 500px; height: 500px"
            :src="previewImg"
            alt="Preview Image"
            ref="imageRef"
          />
        </div>
        <div class="button">
          <h-button @click="sureSava" type="primary">裁剪</h-button>
          <h-button @click="cancel">取消</h-button>
        </div>
      </div>
    </div>
    <!-- preview -->
    <div class="before"></div>
  </div>
</template>

<script setup lang="ts">
import { ref, nextTick } from "vue";
import type { CropperProps, CropperEvent } from "./types";
import HIcon from "../Icon/HIcon.vue";
import Cropper from "cropperjs";
import HButton from "../Button/HButton.vue";

const {
  viewMode = 0,
  dragNode = "crop",
  initialAspectRatio = NaN,
  aspectRatio = NaN,
  preview = "",
  background = true,
  autoCropArea = 0.8,
  zoomOnWheel = true,
} = defineProps<CropperProps>();
const emits = defineEmits<CropperEvent>();
const inputRef = ref<HTMLInputElement>();
const showWindow = ref(false);
const previewImg = ref("");
const imageRef = ref<HTMLImageElement | null>(null);
const myCropper = ref<Cropper | null>(null);
const cropperImage = ref("");

// 选择文件
const handleClick = () => {
  inputRef.value?.click();
};

// 预览图片
const handleChange = async (e: Event) => {
  showWindow.value = true;
  const target = e.target as HTMLInputElement;
  const files = target.files;
  if (files?.length === 0) {
    showWindow.value = false;
  } else {
    previewImg.value = URL.createObjectURL(files![0]);
    emits("imageLoad", previewImg.value);
    await nextTick(() => {
      init();
      emits("ready");
    });
  }
};

// 初始化cropper
const init = () => {
  // @ts-ignore
  myCropper.value = new Cropper(imageRef.value!, {
    viewMode,
    dragNode,
    initialAspectRatio,
    aspectRatio,
    preview,
    background,
    autoCropArea,
    zoomOnWheel,
  });
};

// 处理裁剪
const sureSava = () => {
  cropperImage.value = myCropper
    .value!.getCroppedCanvas({
      imageSmoothingQuality: "high",
    })
    .toDataURL("image/jpg");
  emits("cropper", cropperImage.value);
  showWindow.value = false;
  myCropper.value?.destroy();
};

// 处理取消裁剪
const cancel = () => {
  cropperImage.value = previewImg.value;
  showWindow.value = false;
  myCropper.value?.destroy();
};
</script>

<style scoped></style>
